package ext.tianma.project2.APQP.queue;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.mail.EMailMessage;
import wt.org.WTUser;
import wt.projmgmt.admin.Project2;
import wt.query.QuerySpec;
import wt.util.WTException;
import wt.util.WTProperties;

import com.ptc.projectmanagement.plan.PlanActivity;

import ext.tianma.project2.APQP.service.APQPConfig;
import ext.tianma.util.TMUtil;

public class SendEMail {
	private static final Logger logger = LoggerFactory.getLogger(SendEMail.class);

	public static void email(
			Map<WTUser, List<PlanActivity>> activity) throws WTException, ParseException, IOException, DocumentException {
		if(null != activity && activity.size() > 0) {
			for (Map.Entry<WTUser, List<PlanActivity>> entry : activity.entrySet()) {
				List<PlanActivity> activitys = entry.getValue();

				String userContent = getUserAllContent(activitys);
				String content = getUserContent(userContent);
				String titleStr = "APQP任务启动通知";
				logger.info( entry.getKey().getName() + "的邮件内容>>>> " + content);
				sendEmail(entry.getKey(), content, titleStr);
			}
		}
	}


	public static void emailForDelay(
			Map<WTUser, List<PlanActivity>> activity) throws WTException, ParseException, IOException, DocumentException {
		if(null != activity && activity.size() > 0) {
			for (Map.Entry<WTUser, List<PlanActivity>> entry : activity.entrySet()) {
				List<PlanActivity> activitys = entry.getValue();
				String userContent = getUserAllContent(activitys);
				String content = getUserContent(userContent);
				String titleStr = "APQP任务延期通知";
				logger.info( entry.getKey().getName() + "的邮件内容>>>> " + content);
				sendEmail(entry.getKey(), content, titleStr);
			}
		}
	}

	/**
	 * 推送邮件
	 *
	 * @param userName 用户
	 * @param content  邮件内容
	 * @param titleStr 邮件主题
	 * @return
	 */
	public static boolean sendEmail(WTUser user, String content, String titleStr) {
		try {
			// 获取用户名和邮件地址
			String emailAddress = user.getEMail();
			logger.info("emailAddress>>>>>>>>>" + emailAddress);
			// 邮件内容
			StringBuffer body = new StringBuffer();
			body.append(content);
			// 多个收件人时以 “;” 隔开
			String[] emailTo = "".equals(emailAddress) || emailAddress == null ? null : emailAddress.split(";");
			EMailMessage email = EMailMessage.newEMailMessage();
			email.addEmailAddress(emailTo);

			// 邮件主题
			StringBuffer title = new StringBuffer();
			title.append(titleStr);
			email.setSubject(title.toString());
			email.setMultipartSubtype("text/html;charset=\"UTF-8\"");
			email.addPart(body.toString(), "text/html;charset=\"UTF-8\"");
			email.send(false);
			return true;

		} catch (WTException e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 封装一个用户的数据表
	 *
	 * @param str
	 * @return
	 * @throws IOException 
	 * @throws DocumentException 
	 */
	public static String getUserContent(String str) throws DocumentException, IOException {
        String key = APQPConfig.getKey("PlanDay");
        String url = getUrlLink();
        String des = "  您好，您如下的任务已由系统提前"+key+"天启动，点击"+url+"进入首页待办查看任务：";
		String content = "<table class=\"MsoNormalTable\" border=\"1px solid\" border-collapse=\"collapse\">\r\n"
				+ "<h3 align=\"left\">"+des+"</h3>"
				+ "<tbody><tr><td style=\"padding:.75pt .75pt .75pt .75pt\">\r\n" + "<p style=\"margin:0cm;\r\n"
				+ "	margin-bottom:.0001pt;\r\n" + "	font-size:12.0pt;\r\n"
				+ "	font-family:宋体;text-align:center\" align=\"center\"><b>APQP名称<span lang=\"EN-US\"></span></b></p>\r\n"
				+ "</td><td style=\"padding:.75pt .75pt .75pt .75pt\">\r\n" + "<p style=\"margin:0cm;\r\n"
				+ "	margin-bottom:.0001pt;\r\n" + "	font-size:12.0pt;\r\n"
				+ "	font-family:宋体;text-align:center\" align=\"center\"><b>活动名称<span lang=\"EN-US\"></span></b></p>\r\n"
				+ "</td><td style=\"padding:.75pt .75pt .75pt .75pt\">\r\n" + "<p style=\"margin:0cm;\r\n"
				+ "	margin-bottom:.0001pt;\r\n" + "	font-size:12.0pt;\r\n"
				+ "	font-family:宋体;text-align:center\" align=\"center\"><b>计划开始日期<span lang=\"EN-US\"></span></b></p>\r\n"
				+ "</td><td style=\"padding:.75pt .75pt .75pt .75pt\">\r\n" + "<p style=\"margin:0cm;\r\n"
				+ "	margin-bottom:.0001pt;\r\n" + "	font-size:12.0pt;\r\n"
				+ "	font-family:宋体;text-align:center\" align=\"center\"><b>APQP业务管理员<span lang=\"EN-US\"></span></b></p>\r\n"
				+ "</td><td style=\"padding:.75pt .75pt .75pt .75pt\">\r\n" + "<p style=\"margin:0cm;\r\n"
				+ "	margin-bottom:.0001pt;\r\n" + "	font-size:12.0pt;\r\n"
				+ "	font-family:宋体;text-align:center\" align=\"center\"><b>责任人<span lang=\"EN-US\"></span></b></p>\r\n"
				+ "</td></tr>" + str + "</tbody>\r\n" + "</table>\r\n" + "\r\n";
		return content;
	}
	
	@SuppressWarnings("static-access")
	private static String getUrlLink() throws IOException {
		WTProperties pro = WTProperties.getLocalProperties();
		String localProperties = pro.getProperty("java.rmi.server.hostname").toString();
		StringBuffer sb = new StringBuffer();
		sb.append("http://").append(localProperties).append("/Windchill/navigator/resources/project2/APQP/index.html#/taskList");
		
		String urlLink = "<a href='" + sb.toString() + "' target='_blank'>链接</a>";
		return urlLink;
	}

	/**
	 * 封装用户的所有数据内容
	 *
	 * @param activitys
	 * @return
	 */
	public static String getUserAllContent(List<PlanActivity> activitys) {
		String content = "";
		// activitys 不为空且长度大于0时，遍历activitys追加到content中
		if (activitys != null && activitys.size() > 0) {
			for (PlanActivity activity : activitys) {
				content += getContent(activity);
			}
		}
		return content;
	}

	/**
	 * 封装一条活动内容数据
	 *
	 * @param planActivity
	 * @return
	 */
	public static String getContent(PlanActivity planActivity) {
		if (planActivity == null) {
			return "不存在活动";
		}
		// 获取项目对象
		Project2 project = (Project2) planActivity.getContainer();
		String apqpName = project.getName();
		String planActivityName = planActivity.getName();
		String startDate = TMUtil.timestampToString(planActivity.getStartDate(), "yyyy-MM-dd");
		WTUser pmUser = (WTUser) project.getOwner();
		String businessAdministrator = pmUser.getFullName();
		String responsible = planActivity.getOwnership().getOwner().getFullName();

		String content = "<tr align=\"center\"><td style=\"padding:.75pt .75pt .75pt .75pt\">\r\n"
				+ "<p style=\"margin:0cm;\r\n" + "	margin-bottom:.0001pt;\r\n" + "	font-size:12.0pt;\r\n"
				+ "	font-family:宋体;text-align:center\" align=\"center\"><b>" + apqpName
				+ "<span lang=\"EN-US\"></span></b></p>\r\n" + "</td><td style=\"padding:.75pt .75pt .75pt .75pt\">\r\n"
				+ "<p style=\"margin:0cm;\r\n" + "	margin-bottom:.0001pt;\r\n" + "	font-size:12.0pt;\r\n"
				+ "	font-family:宋体;text-align:center\" align=\"center\"><b>" + planActivityName
				+ "<span lang=\"EN-US\"></span></b></p>\r\n" + "</td><td style=\"padding:.75pt .75pt .75pt .75pt\">\r\n"
				+ "<p style=\"margin:0cm;\r\n" + "	margin-bottom:.0001pt;\r\n" + "	font-size:12.0pt;\r\n"
				+ "	font-family:宋体;text-align:center\" align=\"center\"><b>" + startDate
				+ "<span lang=\"EN-US\"></span></b></p>\r\n" + "</td><td style=\"padding:.75pt .75pt .75pt .75pt\">\r\n"
				+ "<p style=\"margin:0cm;\r\n" + "	margin-bottom:.0001pt;\r\n" + "	font-size:12.0pt;\r\n"
				+ "	font-family:宋体;text-align:center\" align=\"center\"><b>" + businessAdministrator
				+ "<span lang=\"EN-US\"></span></b></p>\r\n" + "</td><td style=\"padding:.75pt .75pt .75pt .75pt\">\r\n"
				+ "<p style=\"margin:0cm;\r\n" + "	margin-bottom:.0001pt;\r\n" + "	font-size:12.0pt;\r\n"
				+ "	font-family:宋体;text-align:center\" align=\"center\"><b>" + responsible
				+ "<span lang=\"EN-US\"></span></b></p>\r\n" + "</td></tr>";
		return content;
	}

	/**
	 * 获取用户的所有任务
	 *
	 * @param projectStates 项目状态
	 * @param planStates    任务状态
	 * @param hierarchy     层级
	 * @return
	 * @throws WTException
	 * @throws ParseException
	 * @throws IOException 
	 * @throws DocumentException 
	 * @throws NullPointerException
	 */
	public static Map<WTUser, List<PlanActivity>> getUserAllTask(QuerySpec qs) throws WTException, ParseException, DocumentException, IOException {
		List<PlanActivity> list = null;
		Map<WTUser, List<PlanActivity>> acts = new HashMap<WTUser, List<PlanActivity>>();
		QueryResult queryResult = PersistenceHelper.manager.find(qs);
		logger.info("qs>>>>>>>>" + qs.toString());
		while (queryResult.hasMoreElements()) {
			Object[] obj = (Object[]) queryResult.nextElement();
			for (int i = 0; i < obj.length; i++) {
				PlanActivity planActivity = (PlanActivity) obj[i];
				WTUser u = (WTUser) planActivity.getOwnership().getOwner().getObject();
				if (acts.containsKey(u)) {
					acts.get(u).add(planActivity);
				} else {
					list = new ArrayList<>();
					list.add(planActivity);
					acts.put(u, list);
				}
			}
		}
		return acts;
	}
}
